﻿/*
Copyright (c) 2007-2011 William POTTIER - AllProgrammic

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
of the Software, and to permit persons to whom the Software is furnished to do so, 
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using NetAccess.Common;
using NetAccess.Common.Exceptions;
using NetAccess.Formatters;
using NetAccess.Message;

namespace NetAccess.Client
{
    /// <summary>
    /// Couche client pour la connexion à un serveur
    /// </summary>
    public abstract partial class ClientLayer : IContextLogger
    {
        #region Fields
        /// <summary>
        /// Configuration 
        /// </summary>
        private ClientConfiguration _configuration;
        /// <summary>
        /// TCP service socket
        /// </summary>
        private Socket _socketTCPService;
        /// <summary>
        /// Connect timer
        /// </summary>
        private Timer _timerConnect;
        /// <summary>
        /// Manual reset event for incommig data
        /// </summary>
        private ManualResetEvent _waitReceive;
        /// <summary>
        /// Manual reset event for ping system
        /// </summary>
        private ManualResetEvent _pongWait;
        /// <summary>
        /// Message formatter
        /// </summary>
        private MessageFormatter _messageFormatter;
        /// <summary>
        /// Disconnection informations (if disconnection come from server side
        /// </summary>
        private NetworkMessage _disconnectDatas;
        #endregion

        #region Properties
        /// <summary>
        /// Client Status
        /// </summary>
        public ClientState State { get; private set; }
        /// <summary>
        /// Remote server informations
        /// </summary>
        public ServiceData RemoteServer { get; private set; }
        #endregion

        /// <summary>
        /// Constructor
        /// </summary>
        protected ClientLayer()
        {
            State = ClientState.Disconnected;
            _pongWait = new ManualResetEvent(false);
        }

        #region Connexion
        /// <summary>
        /// Start connexion with ServiceData
        /// </summary>
        /// <param name="service"></param>
        public void Connect(ServiceData service)
        {
            Connect(service.ToConfiguration());
        }


        /// <summary>
        /// Start connexion with configuration
        /// </summary>
        public void Connect(ClientConfiguration config)
        {
            if (State != ClientState.Disconnected) { return; }

            // Lock configuration
            _configuration = (ClientConfiguration)config.Clone();
            _configuration.LockConfiguration();

            if (_configuration.TCPServiceEndPoint == null)
            {
                throw new Exception("Unable to connect. Server IP or Port invalid.");
            }
            
            // Set connecting state
            State = ClientState.Connecting;

            // Createa socket
            _socketTCPService = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            if (_configuration.SendBufferSize > 0)
                _socketTCPService.SendBufferSize = _configuration.SendBufferSize;
            if (_configuration.ReceiveBufferSize > 0)
                _socketTCPService.ReceiveBufferSize = _configuration.ReceiveBufferSize;

            _socketTCPService.BeginConnect(_configuration.IP, _configuration.TCPServicePort,
                                           ConnectCallback, _socketTCPService);

            // Create message formatter
            _messageFormatter = new MessageFormatter(_socketTCPService.SendBufferSize);
        }

        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                _socketTCPService.EndConnect(ar);
            }
            catch (SocketException se)
            {
                Logger.Instance.Debug(se, this);
                State = ClientState.Disconnected;
                OnConnectComplete(ConnectionResult.Error, exception: se);
                return;
            }
            catch (Exception ex)
            {
                Logger.Instance.Debug(ex, this);
                State = ClientState.Disconnected;
                return;
            }

            _timerConnect = new Timer(ConnectTimeout, null, _configuration.ConnectTimeout, TimeSpan.FromMilliseconds(-1));
            RemoteServer = new ServiceData { IP = _configuration.IP, TCPPort = _configuration.TCPServicePort, UseCompression = false, AvailableSlots = 0, NbClient = 0, PublicKeyString = null, ServiceName = "", UDPPort = 0, UseCrypt = false };

            ThreadPool.QueueUserWorkItem(Receive);

            // Send HandShake request to complete connection
            var additionalsData = PrepareHandShake();
            Send(new InternalMessage(InternalMessageIdentifier.HandShake, null, additionalsData));
        }

        protected virtual object[] PrepareHandShake() { return new object[0]; }

        private void ConnectTimeout(object state)
        {
            if (State != ClientState.Connecting) return;

            // Abandonne la connexion
            State = ClientState.Disconnected;
            OnConnectComplete(ConnectionResult.TimeOut);
            Disconnect(false);
        }
        #endregion

        #region Deconnexion
        /// <summary>
        /// Déconnecte le client du server
        /// </summary>
        public void Disconnect()
        {
            Disconnect(true);
        }
               
        private void Disconnect(bool userRequest)
        {
            lock (this)
            {
                if (State == ClientState.Connected || State == ClientState.Connecting)
                {
                    bool raise = false;
                    if (!userRequest && State == ClientState.Connected)
                        raise = true;

                    State = ClientState.Disconnecting;

                    if (_socketTCPService != null)
                        _socketTCPService.Close();
                    _socketTCPService = null;

                    if (_waitReceive != null)
                        _waitReceive.Close();

                    if (_pongWait != null)
                        _pongWait.Close();

                    if (_timerConnect != null)
                        _timerConnect.Dispose();

                    _waitReceive = null;
                    _pongWait = null;
                    _timerConnect = null;

                    State = ClientState.Disconnected;

                    if (raise)
                    {
                        if (_disconnectDatas != null)
                        {
                            OnConnexionLost(_disconnectDatas);
                            _disconnectDatas = null;
                        }
                        else
                            OnConnexionLost();
                    }
                }
            }
        }
        #endregion

        #region Reception
        private void Receive(object state)
        {
            _waitReceive = new ManualResetEvent(false);

            while (State == ClientState.Connecting || State == ClientState.Connected)
            {
                try
                {
                    _waitReceive.Reset();
                }
                catch (ObjectDisposedException) { break; }
                catch (NullReferenceException) { break; }

                try
                {
                    var buffer = new byte[_socketTCPService.ReceiveBufferSize];
                    _socketTCPService.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, buffer);
                }
                catch (ObjectDisposedException) { break; }
                catch (NullReferenceException) { break; }
                catch (SocketException se)
                {
                    if (se.SocketErrorCode == SocketError.ConnectionReset)
                    {
                        Disconnect(false);
                        break;
                    }
                    
                    Logger.Instance.Error(se);
                }

                try
                {
                    _waitReceive.WaitOne();
                }
                catch (ObjectDisposedException) { break; }
                catch (NullReferenceException) { break; }
            }
        }

        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                _waitReceive.Set();
            }
            catch (ObjectDisposedException) { return; }
            catch (NullReferenceException) { return; }

            var numread = 0;
            var buffer = new byte[0];

            try
            {
                numread = _socketTCPService.EndReceive(ar);
                buffer = (byte[])ar.AsyncState;
            }
            catch (ObjectDisposedException) { return; }
            catch (NullReferenceException) { return; }
            catch (SocketException se)
            {
                if (se.SocketErrorCode == SocketError.ConnectionReset)
                {
                    Disconnect(false);
                }
                else
                {
                    Console.WriteLine(se.ToString());
                }
            }

            if (numread > 0)
            {
                // Transmet les données lu au formatter
                _messageFormatter.AddDataToReception(buffer, numread);

                // Lance le traitement de la file de message
                ProcessMessage(_messageFormatter.ProcessIncommingMessages());
            }

        }

        private void ProcessMessage(Queue<InternalMessage> queue)
        {
            // thread safe
            lock (this)
            {
                while(queue.Count > 0)
                {
                    InternalMessage message = queue.Dequeue();

                    switch (message.MessageIdentifier)
                    {
                        case InternalMessageIdentifier.TransmitData:
                            if (State == ClientState.Connected)
                            {
                                // Isolate message processing
                                try
                                {
                                    DataReceived((NetworkMessage)message.MessageData[0]);
                                }
                                catch (Exception ex)
                                {
                                    Logger.Instance.Error(new NetAccessException("An error occured in DataReceived processing. See InnerException for more information.", ex), this);
                                }
                                continue;
                            }
                            continue;
                        case InternalMessageIdentifier.ServerConnection:
                            var result = (ConnectionResult)message.MessageData[0];
                            var info = (string)message.MessageData[1];
                            switch (result)
                            {
                                case ConnectionResult.Reject:
                                case ConnectionResult.ServerFull:
                                    // Disconnect
                                    Disconnect(false);
                                    // Notify failure
                                    OnConnectComplete(result, exception: new NetAccessException(info));
                                    continue;
                                case ConnectionResult.Accept:
                                    var applicationId = (string)message.MessageData[2];
                                    if (applicationId != _configuration.ApplicationIdentifier)
                                    {
                                        Disconnect(false);

                                        OnConnectComplete(ConnectionResult.Reject, exception: new ApplicationIdentifierNotMatchException(_configuration.ApplicationIdentifier, applicationId));
                                        continue;
                                    }

                                    RemoteServer.ServiceName = info;
                                    RemoteServer.UseCompression = (bool)message.MessageData[3];

                                    State = ClientState.Connected;

                                    if (_configuration.IsEnableEncryption)
                                    {
                                        RemoteServer.UseCrypt = true;
                                        RemoteServer.PublicKeyString = _configuration.ServerPublicKeyString;

                                        Send(new InternalMessage(InternalMessageIdentifier.TransmitPublicKey, null));
                                    }

                                    OnConnectComplete(ConnectionResult.Accept, info);
                                    continue;
                            }
                            break;
                        case InternalMessageIdentifier.Ping:
                            Send(new InternalMessage(InternalMessageIdentifier.Pong));
                            continue;
                        case InternalMessageIdentifier.Pong:
                            _pongWait.Set();
                            continue;
                        case InternalMessageIdentifier.DestroyClient:
                            State = ClientState.Disconnecting;
                            _disconnectDatas = (NetworkMessage)message.MessageData[0];
                            continue;
                    }
                }
            }
        }

        /// <summary>
        /// Override to handle received message
        /// </summary>
        /// <param name="message"></param>
        public virtual void DataReceived(NetworkMessage message) { }
        #endregion

        #region Sending
        /// <summary>
        /// Send Message
        /// </summary>
        /// <param name="message"></param>
        /// <param name="crypt"></param>
        public void Send(NetworkMessage message, bool crypt = false)
        {
            Send(new InternalMessage(InternalMessageIdentifier.TransmitData, message));
        }

        private void Send(InternalMessage imessage)
        {
            if (State != ClientState.Connected && State != ClientState.Connecting)
                return;

            Queue<byte[]> file =  _messageFormatter.Prepare(imessage, RemoteServer.UseCompression);

            while(file.Count > 0)
            {
                byte[] buffer = file.Dequeue();
                try
                {
                    _socketTCPService.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, SendTCPCallback, buffer);
                }
                catch (ObjectDisposedException) { return; }
                catch (NullReferenceException) { return; }
                catch (SocketException se)
                {
                    if (se.SocketErrorCode == SocketError.ConnectionReset)
                    {
                        Disconnect(false);
                    }
                    else
                    {
                        Logger.Instance.Error(se, this);
                    }
                }
            }
        }

        private void SendTCPCallback(IAsyncResult ar)
        {
            if (State != ClientState.Connected)
                return;

            try
            {
                _socketTCPService.EndSend(ar);
            }
            catch (ObjectDisposedException) { return; }
            catch (NullReferenceException) { return; }
            catch (IOException)
            {
                Disconnect(false);
            }
            catch (SocketException se)
            {
                if (se.SocketErrorCode == SocketError.ConnectionReset)
                {
                    Disconnect(false);
                }
                else
                {
                    Logger.Instance.Error(se, this);
                }
            }
        }
        #endregion

        #region Abstract Event Method

        /// <summary>
        /// Method called when the connection process complete
        /// </summary>
        /// <param name="result">resul</param>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        protected virtual void OnConnectComplete(ConnectionResult result, string message = null, Exception exception = null) { }

        /// <summary>
        /// Method called when the connexion was lost
        /// </summary>
        /// <param name="datas">A network message that may be contain some information about connection closing.</param>
        protected virtual void OnConnexionLost(NetworkMessage datas = null) { }
        #endregion

        #region IContextLogger
        /// <summary>
        /// Gets context name
        /// </summary>
        /// <returns></returns>
        public string GetName()
        {
            return String.Format("ClientLayer");
        }
        #endregion
    }
}
